import React, { useEffect, useMemo, useState } from 'react';
import { Table, Button, Modal, Form, Pagination, Popconfirm, message } from 'antd';
import { filterFormWithEmptyValue } from '@/router/util/params';
import * as XLSX from 'xlsx';
import { formatDateTime } from '@/utils/date';

interface MyTableProps {
  title: string;
  requestCount?: boolean;
  getDataApi: (params?: any) => Promise<DataResponse>;
  addDataApi: (params?: any) => Promise<DataResponse>;
  deleteApi: (params?: any) => Promise<DataResponse>;
  updateDataApi: (params?: any) => Promise<DataResponse>;
  uploadApi?: (params?: any) => Promise<DataResponse>;
  columns: any[]; // 这里使用 any 类型是因为 Ant Design 的表格组件的列定义需要的类型比较特殊，暂时无法使用泛型描述
  onChange: (dataSource: any) => void;
  onRecordChange: (data: any, form: any) => void;
  setAddForm?: (form: any) => void;
  SerchBar: JSX.Element;
  AddForm?: JSX.Element;
  EditForm?: JSX.Element;
}

interface DataResponse {
  code: number;
  data: any[];
  message: string;
  total?: number;
}

const { confirm } = Modal;

function CommonTable({
  title,
  getDataApi,
  deleteApi,
  uploadApi,
  onChange,
  onRecordChange,
  addDataApi,
  updateDataApi,
  setAddForm,
  columns,
  SerchBar,
  AddForm,
  EditForm,
  requestCount
}: MyTableProps) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [formData, setFormData] = useState({});
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [requestId, setRequestId] = useState(0);
  const [loading, setLoading] = useState(false);
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const [actionType, setActionType] = useState('');

  useEffect(() => {
    setLoading(true);
    getData();
  }, [requestId, requestCount]);

  const getData = () => {
    const params = {
      ...filterFormWithEmptyValue(form1.getFieldsValue()),
      page: currentPage,
      size: pageSize
    };
    getDataApi(params).then((res) => {
      setDataSource(res.data);
      setTotal(res?.total ?? 0);
      onChange(res.data);
      setLoading(false);
    });
  };

  const deleteAction = (rows: number[]) => {
    deleteApi({
      rows
    })
      .then(() => {
        setSelectedRowKeys([]);
        setCurrentPage(1);
      })
      .then(getData);
  };

  const handleBatchDelete = () => {
    confirm({
      title: '确认删除?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => deleteAction(selectedRowKeys)
    });
  };

  const handleEdit = (record: any) => {
    onRecordChange(record, form2);
    setModalVisible(true);
    setActionType('edit');
  };

  const handleExportExcel = () => {
    getDataApi().then((res) => {
      const data = res.data?.map((it) => ({
        ...it,
        created_at: formatDateTime(it.created_at),
        updated_at: formatDateTime(it.updated_at)
      }));
      const headers = Object.keys(data[0]); // 获取表格列名
      const columns = headers
        .filter((header) => header !== 'created_at' && header !== 'updated_at') // 过滤掉 created_at 和 updated_at 列
        .concat(['created_at', 'updated_at']); // 将 created_at 和 updated_at 列添加到列末尾
      const worksheet = XLSX.utils.json_to_sheet(data ?? [], {
        header: columns // 指定表格列名的顺序
      });
      const workbook = XLSX.utils.book_new(); // 创建一个新的工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); // 将工作表添加到工作簿中
      XLSX.writeFile(workbook, `${title}列表.xlsx`); // 将工作簿保存为 Excel 文件
    });
  };

  const clear = () => {
    setRequestId(requestId + 1);
    setCurrentPage(1);
    setModalVisible(false);
    form1.resetFields();
    form2.resetFields();
  };

  const handleFinish = (values: any) => {
    // TODO: 处理表单提交
    if (actionType === 'add') {
      addDataApi(values).then(() => {
        message.success("数据添加成功！！")
        clear();
      });
    }

    if (actionType === 'edit') {
      updateDataApi(values).then(() => {
        message.success("该条记录编辑成功！！")
        clear();
      });
    }
  };
  const handleModalCancel = () => {
    setModalVisible(false);
    setActionType('');
  };
  const handlePageChange = (page: number, size: number) => {
    if (size === pageSize) {
      setRequestId(requestId + 1);
      setCurrentPage(page);
    }
  };
  const handleShowSizeChange = (_: number, size: number) => {
    setCurrentPage(1);
    setPageSize(size);
    setRequestId(requestId + 1);
  };
  const handleSelectChange = (selectedRowKeys: any[]) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const handleFileChange = (file: any) => {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      const workbook = XLSX.read(e.target.result, { type: 'binary' });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      let sheetData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      sheetData.forEach((row: any) => {
        if (typeof row.answer === 'string') {
          row.answer = JSON.stringify(row.answer);
        }
        if (typeof row.analysis === 'string') {
          row.analysis = JSON.stringify(row.analysis);
        }
      });
      uploadApi?.({
        rows: sheetData
      }).then(() => {
        setRequestId(requestId + 1);
      });
    };
    reader.readAsBinaryString(file);
  };

  const handleFileUpload = (event: any) => {
    const file = event.target.files[0];
    handleFileChange(file);
  };

  const handleButtonClick = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx, .xls, .csv';
    input.onchange = (event) => handleFileUpload(event);
    input.click();
  };

  const tableCloumns = useMemo(
    () => [
      ...columns,
      {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at',
        width: '180px',
        align: 'center',
        render: (_: string, v: any) => formatDateTime(v.created_at)
      },
      {
        title: '更新时间',
        dataIndex: 'updated_at',
        key: 'updated_at',
        width: '180px',
        align: 'center',
        render: (_: string, v: any) => formatDateTime(v.updated_at)
      },
      {
        title: '操作',
        key: 'action',
        width: '150px',
        align: 'center',
        fixed: 'right',
        render: (_: any, v: any) => (
          <div style={{ display: 'flex' }}>
            <Popconfirm
              placement="left"
              title="是否删除该条数据"
              onConfirm={() => deleteAction([v._id])}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link">删除</Button>
            </Popconfirm>

            {EditForm && (
              <Button type="link" onClick={() => handleEdit(v)}>
                编辑
              </Button>
            )}
          </div>
        )
      }
    ],
    [columns]
  );

  const handleAdd = () => {
    setAddForm?.(form2);
    setModalVisible(true);
    setActionType('add');
  };

  return (
    <div style={{ padding: '10px', background: '#fff', borderRadius: '5px' }}>
      <div style={{ display: 'flex', marginTop: '10px' }}>
        <div style={{ flex: 1, display: 'flex', justifyContent: 'space-between', marginTop: '5px' }}>
          <div style={{ lineHeight: '40px' }}>
            <Form
              form={form1}
              style={{ display: 'flex', flexWrap: 'wrap' }}
              onFinish={() => setRequestId(requestId + 1)}
            >
              {SerchBar}
            </Form>
          </div>
          <Button type="primary" loading={loading} onClick={() => setRequestId(requestId + 1)}>
            查询
          </Button>
        </div>
        <div
          style={{
            marginBottom: '16px',
            width: '350px',
            display: 'flex',
            justifyContent: 'flex-end',
            flexWrap: 'wrap'
          }}
        >
          {AddForm && (
            <Button style={{ margin: '5px' }} type="primary" onClick={handleAdd}>
              新增
            </Button>
          )}
          <Button
            style={{ margin: '5px' }}
            type="primary"
            danger
            onClick={handleBatchDelete}
            disabled={!selectedRowKeys.length}
          >
            批量删除
          </Button>
          {uploadApi && (
            <Button style={{ margin: '5px' }} onClick={handleButtonClick}>
              表格导入
            </Button>
          )}
          <Button style={{ margin: '5px' }} onClick={handleExportExcel} disabled={!total}>
            导出
          </Button>
        </div>
      </div>

      <Table
        rowKey="_id"
        loading={loading}
        dataSource={dataSource}
        scroll={{ x: '1000px', y: 'calc(100vh - 320px)' }}
        columns={tableCloumns}
        rowSelection={{ selectedRowKeys, onChange: handleSelectChange }}
        pagination={false}
        footer={() => (
          <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
            {total ? `总计${total}条数据` : null}
            <Pagination
              showSizeChanger
              onChange={handlePageChange}
              onShowSizeChange={handleShowSizeChange}
              current={currentPage}
              total={total}
            />
          </div>
        )}
      />
      <Modal
        title={(actionType === 'add' ? '新增' : '编辑') + (title ?? '')}
        open={modalVisible}
        destroyOnClose
        okText="确认"
        style={{ width: '600px' }}
        centered
        cancelText="取消"
        onOk={form2.submit}
        onCancel={handleModalCancel}
      >
        {actionType === 'add' && (
          <Form form={form2} onFinish={handleFinish} style={{ padding: '10px' }}>
            {AddForm}
          </Form>
        )}
        {actionType === 'edit' && (
          <Form form={form2} onFinish={handleFinish} style={{ padding: '10px' }}>
            {EditForm}
          </Form>
        )}
      </Modal>
    </div>
  );
}

export default CommonTable;
